from collections import deque

from apps.task.re_pattern import RePattern


class NameOneParse(object):

    def __init__(self):
        self.person_info_dict: dict = {}
        # 正在处理的index 和 line
        self.now_deal_index_line = deque(maxlen=5)
        self.init_dicts()

    def init_dicts(self):
        """
        这些字段暂时不解析，后面有可能从人物辅名解析出来
        Returns:

        """
        self.person_info_dict["person_variant_name"] = ''
        self.person_info_dict["person_auxiliary_name"] = []
        self.person_info_dict["person_dynasty"] = ''
        self.person_info_dict["person_gender"] = ''
        self.person_info_dict["person_zi"] = ''
        self.person_info_dict["person_hao"] = ''
        self.person_info_dict["person_knight"] = ''
        self.person_info_dict["person_position"] = ''
        self.person_info_dict["person_posthumous_title"] = ''
        self.person_info_dict["person_biography"] = ''
        self.person_info_dict["person_source_raw"] = ''
        self.person_info_dict["person_source"] = []
        self.person_info_dict["person_note"] = ''

    def split_line(self, one_text: str):
        """
        将数据按行分割，并按照行开始的符号将数分为多个块
        :param one_text:  输入单条数据的str
        :return:
        """
        list_1, list_2, list_3, list_4 = [], [], [], []
        line_list = one_text.split("\n")
        list_tmp = list_1
        for index, line in enumerate(line_list):
            line = line.strip()
            self.now_deal_index_line.append((index, line))
            if line.startswith("Ａ"):
                list_tmp = list_1
            if line.startswith("%"):
                list_tmp = list_2
            if line.startswith("#"):
                list_tmp = list_3
            if line.startswith("◎"):
                list_tmp = list_4
            list_tmp.append((index, line))

        return list_1, list_2, list_3, list_4

    def parse_list_1(self, list_1):
        """
        list_1 数据格式如下：
        Ａ14155@胡世安%[清](處靜　菊潭　秀巖)
        一般认为  该list里面只存在一行
        """
        self.now_deal_index_line.append(list_1[0])
        person_name_id, other_info = list_1[0][1].split("@")
        person_name, other_info2 = other_info.split("%")
        # 朝代  []中提取的内容
        person_dynasty = RePattern.extract_square_bracket_contents(other_info2)
        # 輔名 () 中 提取的类容
        person_auxiliary_name = RePattern.extract_square_parentheses_contents(other_info2)
        self.person_info_dict["person_id"] = person_name_id
        self.person_info_dict["person_name"] = person_name

        if person_dynasty:
            self.person_info_dict["person_dynasty"] = person_dynasty[0]
        else:
            self.person_info_dict["person_dynasty"] = ""
        if person_auxiliary_name:
            self.person_info_dict["person_auxiliary_name"] = person_auxiliary_name[0].split("\u3000")
        else:
            self.person_info_dict["person_auxiliary_name"] = person_auxiliary_name

    def parse_list_2(self, list_2):
        """
        list_2 每行为list里的一个数据 数据格式如下 ：
        %胡世安﹒四川井研人﹒字處靜﹒號秀巖﹒別號菊潭﹒萬曆二十年（壬辰）生﹒
        明崇禎元年進士﹒累官詹事府少詹事﹒順治初降清﹒授原官﹒十五年授武英殿大學士﹒
        兼兵部尚書﹒康熙初官至祕書院大學士﹒康熙二年（癸卯）卒﹒著有<秀巖集><衍囈語><明覺聰禪師語錄序>﹒

        所有数据合为一个字段
        """
        self.now_deal_index_line.extend(list_2)
        list_2 = [line for index, line in list_2]
        person_biography = "".join(list_2)
        person_biography = person_biography.lstrip("%")
        self.person_info_dict["person_biography"] = person_biography

    def parse_list_3(self, list_3):
        """
        list_3 每行为list里的一个数据 数据格式如下 ：
        #清史$128清史$152清史$153清史$155清史$4221清史$4321清史$4354清史$4357清史$4378
        清史$6105清史$6107清史$6108清史$6109清史$6329清史$6331清史$6332清史$6334
        清史$6337清史$6338清史$6339清史$6341清史$6343清史$6346清史$6350清史$6353
        清史$8905清史$9501清史$9636
        #明季北略
        """

        self.person_info_dict["person_source_raw"] = "".join([item[1] for item in list_3])
        person_source_list = []
        try:
            for item in list_3:
                self.now_deal_index_line.append(item)
                if not item[1]:
                    continue
                item = item[1]
                item = item.lstrip("#")
                item1 = RePattern.number_to_espacio(item)
                item1 = item1.replace("$", "")
                work_name = None
                for i in item1.split(" "):
                    if i != "":
                        work_name = i
                        break
                if not work_name:
                    Exception("书名规则解析错误")
                work_name_lists = item.split(work_name)
                if work_name_lists and work_name_lists[0].strip() == "":
                    work_name_lists = work_name_lists[1:]
                for page_info in work_name_lists:
                    dict_person_source = {}
                    label = ""
                    if page_info == "":
                        page, page_alt = "", ""
                    else:
                        page_list = page_info.split("$")
                        if len(page_list) == 1:
                            page = page_list[0].strip()
                            page_alt = ""
                            if page and not page.isdigit():
                                raise Exception("1 page 存在其他label,page 是 " + str(page) + ";")
                        elif len(page_list) == 2:
                            page, page_alt = page_list
                            page = page.strip()
                            if page_alt.find("*") > -1:
                                page_alt = page_alt.replace("*", "")
                                # 在这里添加一个字段
                                label = "*"
                            if not page_alt.isdigit():
                                raise Exception("page_alt 存在其他label,page_alt 是 " + str(page_alt) + ";")
                            if page and not page.isdigit():
                                raise Exception("2 page 存在其他label,page 是 " + str(page) + ";")
                        else:
                            raise Exception("page 解析长度错误,数据为: " + str(page_info))
                    dict_person_source["work_name"] = work_name
                    dict_person_source["page"] = str(page)
                    dict_person_source["page_alt"] = str(page_alt)
                    dict_person_source["label"] = label
                    person_source_list.append(dict_person_source)
            self.person_info_dict["person_source"] = person_source_list
        except:
            # 根据讨论，由于格式不固定，无法解析的数据就为空，这样可能存在一种情况，就是该格式是可以解析的，但里面有错误需要修复，
            # 目前讨论的结果就是这样简单粗暴的解决问题。 20231228
            self.person_info_dict["person_source"] = person_source_list

    def parse_list_4(self, list_4):
        """
         list_1 数据格式如下：
         ◎全上古三代秦漢三國六朝文第9頁
        一般认为  该list里面只存在一行
        :param list_4:
        :return:
        """
        if list_4:
            self.now_deal_index_line.extend(list_4)
            list_4 = [line for index, line in list_4]
            self.person_info_dict["person_note"] = list_4[0].lstrip("◎")
        else:
            self.person_info_dict["person_note"] = ""

    def deal_special(self, one_text):
        """
        特殊情况处理
        :return:
        """
        if one_text.strip().split("@")[1].find("?") > -1:
            person_name_id, person_name = one_text.strip().split("@")
            self.person_info_dict["person_id"] = person_name_id
            self.person_info_dict["person_name"] = "未收_____"
            return True
        return False

    def run_parse(self, one_text):
        self.person_info_dict = {}
        self.init_dicts()
        # 处理特殊情况
        if self.deal_special(one_text):
            return self.person_info_dict
        # 将 人的信息分为4部分解析
        list_1, list_2, list_3, list_4 = self.split_line(one_text)
        self.parse_list_1(list_1)
        self.parse_list_2(list_2)
        self.parse_list_3(list_3)
        self.parse_list_4(list_4)
        return self.person_info_dict
